﻿// ******************************************************************
// * Copyright(c)  Steven Lu
// * Description   : Entity_QC_IQC_ORDER
// * CreateDate    : 2012/4/15 0:42:00
// * Creater       : CodeSmith
// * LastChangeDate: 2012/4/15 0:42:00
// * LastChanger   : 2012/4/15 0:42:00
// * Version Info  : 1.0 For ESOL
// ******************************************************************

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Suzsoft.Smart.Data;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Common;

namespace ESOL.Business.Chk
{
    /// <summary>
    /// QcIqcOrder
    /// </summary>
    public partial class QcIqcOrderBs
    {
        #region GetByID
        /// <summary>
        /// Get Entity
        /// </summary>
        /// <param name="objQcIqcOrderEntity">Entity</param>
        /// <returns>Entity</returns>
        public static QcIqcOrderEntity GetQcIqcOrder(QcIqcOrderEntity objQcIqcOrderEntity)
        {
            return DataAccess.SelectSingle<QcIqcOrderEntity>(objQcIqcOrderEntity);
        }
        #endregion


        #region Insert
        /// <summary>
        /// Insert Data
        /// </summary>
        /// <param name="objQcIqcOrderEntity">Entity</param>
        /// <returns>true Insert Succeed; false Insert Fail</returns>
        public static bool InsertQcIqcOrder(QcIqcOrderEntity objQcIqcOrderEntity)
        {
            return DataAccess.Insert(objQcIqcOrderEntity);
        }

        public static bool InsertQcIqcOrder(List<QcIqcOrderEntity> objQcIqcOrderEntityList)
        {
            return DataAccess.Insert(objQcIqcOrderEntityList);
        }
        #endregion


        #region Update
        /// <summary>
        /// Update Data
        /// </summary>
        /// <param name="objQcIqcOrderEntity">Entity</param>
        /// <returns>true Update Succeed; false Update Fail</returns>
        public static bool UpdateQcIqcOrder(QcIqcOrderEntity objQcIqcOrderEntity)
        {
            return DataAccess.Update(objQcIqcOrderEntity);
        }

        public static bool UpdateQcIqcOrder(List<QcIqcOrderEntity> objQcIqcOrderEntityList)
        {
            return DataAccess.Update<QcIqcOrderEntity>(objQcIqcOrderEntityList);
        }
        #endregion


        #region Delete
        /// <summary>
        /// Delete Data
        /// </summary>
        /// <param name="objQcIqcOrderEntity">Entity</param>
        /// <returns>true Delete Succeed; false Delete Fail</returns>
        public static bool DeleteQcIqcOrder(QcIqcOrderEntity objQcIqcOrderEntity)
        {
            return DataAccess.Delete(objQcIqcOrderEntity);
        }

        public static bool DeleteQcIqcOrder(List<QcIqcOrderEntity> objQcIqcOrderEntityList)
        {
            return DataAccess.Delete<QcIqcOrderEntity>(objQcIqcOrderEntityList);
        }
        #endregion


        #region GetAll
        /// <summary>
        /// Get All Data
        /// </summary>
        /// <returns>Back All Data<returns>
        public static DataSet GetQcIqcOrderAll()
        {
            return DataAccess.SelectAllDataSet<QcIqcOrderEntity>();
        }
        /// <summary>
        /// Get All Data List
        /// </summary>
        /// <returns>Back All Data List<returns>
        public static List<QcIqcOrderEntity> GetQcIqcOrderAllList()
        {
            return DataAccess.SelectAll<QcIqcOrderEntity>();
        }
        #endregion

        #region Functions
        public static QcIqcOrderEntity GetIqcOrderByID(string sID)
        {
            if (string.IsNullOrEmpty(sID))
                return null;
            QcIqcOrderEntity m = new QcIqcOrderEntity();
            m.OrderId = sID;
            return DataAccess.SelectSingle<QcIqcOrderEntity>(m);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ActionType"></param>
        /// <param name="entity"></param>
        /// <param name="dtMain"></param>
        /// <param name="dtDetail"></param>
        /// <param name="listDelMain"></param>
        /// <param name="listDelDetail"></param>
        /// <returns></returns>
        public static bool SaveIqcOrder(string ActionType,QcIqcOrderEntity entity,DataTable dtMain,DataTable dtDetail,
            List<DataRow> listDelMain,List<DataRow> listDelDetail)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    if (ActionType.Equals("New"))
                    {
                        string code = "";
                        if (MstCodeRuleBs.GetCurrentOrderCode("CheckingOrder", out code) == false)
                        {
                            broker.RollBack();
                            throw new Exception("自动生成质检单号失败！");
                        }
                        entity.OrderCode = code;
                        DataAccess.Insert(entity, broker);
                    }
                    else
                    {
                        entity.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                        entity.LastModifiedDate = DateTime.Now;
                        DataAccess.Update(entity, broker);
                    }

                    List<QcIqcOrderItemEntity> listItemNew = new List<QcIqcOrderItemEntity>();
                    List<QcIqcOrderItemEntity> listItemModify = new List<QcIqcOrderItemEntity>();
                    List<QcIqcOrderItemEntity> listItemDel = new List<QcIqcOrderItemEntity>();
                    if (ActionType.Equals("New"))
                    {
                        foreach (DataRow dr in dtMain.Rows)
                        {
                            QcIqcOrderItemEntity m = new QcIqcOrderItemEntity(dr);
                            listItemNew.Add(m);
                        }
                    }
                    if (ActionType.Equals("Modify"))
                    {
                        foreach (DataRow dr in dtMain.Rows)
                        {
                            if (dr.RowState == DataRowState.Modified)
                            {
                                QcIqcOrderItemEntity m = new QcIqcOrderItemEntity(dr);
                                listItemModify.Add(m);
                            }
                        }
                    }
                    foreach (DataRow dr in listDelMain)
                    {
                        QcIqcOrderItemEntity m = new QcIqcOrderItemEntity(dr);
                        listItemDel.Add(m);
                    }

                    List<QcIqcOrderItemDetailEntity> listItemDetailNew = new List<QcIqcOrderItemDetailEntity>();
                    List<QcIqcOrderItemDetailEntity> listItemDetailModify = new List<QcIqcOrderItemDetailEntity>();
                    List<QcIqcOrderItemDetailEntity> listItemDetailDel = new List<QcIqcOrderItemDetailEntity>();
                    if (ActionType.Equals("New"))
                    {
                        foreach (DataRow dr in dtDetail.Rows)
                        {
                            QcIqcOrderItemDetailEntity m = new QcIqcOrderItemDetailEntity(dr);
                            listItemDetailNew.Add(m);
                        }
                    }
                    if (ActionType.Equals("Modify"))
                    {
                        foreach (DataRow dr in dtDetail.Rows)
                        {
                            if (dr.RowState == DataRowState.Modified)
                            {
                                QcIqcOrderItemDetailEntity m = new QcIqcOrderItemDetailEntity(dr);
                                listItemDetailModify.Add(m);
                            }
                            if (dr.RowState == DataRowState.Added)
                            {
                                QcIqcOrderItemDetailEntity m = new QcIqcOrderItemDetailEntity(dr);
                                listItemDetailNew.Add(m);
                            }
                        }
                    }
                    foreach (DataRow dr in listDelDetail)
                    {
                        QcIqcOrderItemDetailEntity m = new QcIqcOrderItemDetailEntity(dr);
                        listItemDetailDel.Add(m);
                    }
                    DataAccess.Delete<QcIqcOrderItemDetailEntity>(listItemDetailDel, broker);
                    DataAccess.Update<QcIqcOrderItemDetailEntity>(listItemDetailModify, broker);
                    DataAccess.Insert<QcIqcOrderItemDetailEntity>(listItemDetailNew, broker);

                    DataAccess.Delete<QcIqcOrderItemEntity>(listItemDel, broker);
                    DataAccess.Update<QcIqcOrderItemEntity>(listItemModify, broker);
                    DataAccess.Insert<QcIqcOrderItemEntity>(listItemNew, broker);

                    //假如无不良，自动生成入库单申请单
                    if (entity.ResultTag == 0)
                    {
                        InvImportOrderEntity m = new InvImportOrderEntity();
                        m.ImportOrderId = Guid.NewGuid().ToString();
                        m.OrderType = "IMT01";
                        string code = "";
                        if (MstCodeRuleBs.GetCurrentOrderCode("InvImportOrder", out code) == false)
                        {
                            broker.RollBack();
                            throw new Exception("自动生成质检单号失败！");
                        }
                        m.OrderCode = code;
                        m.OrderDate = DateTime.Now.ToString("yyyy-MM-dd");
                        m.OrderPerson = Common.CommonParameter.CurrentUser.PersonId;
                        m.RelatedOrder = entity.OrderId;
                        m.CreatedBy = Common.CommonParameter.CurrentUser.PersonId;
                        m.CreatedDate = DateTime.Now;
                        m.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                        m.LastModifiedDate = DateTime.Now;
                        m.Remark = "来料质检完成后，系统自动产生";
                        m.Status = "IMO01";

                        List<InvImportItemEntity> list = new List<InvImportItemEntity>();
                        foreach (DataRow dr in dtMain.Rows)
                        {
                            InvImportItemEntity m2 = new InvImportItemEntity();
                            m2.ImportItemId = Guid.NewGuid().ToString();
                            m2.ImportOrderId = m.ImportOrderId;
                            string sql = @"select ppoi.PRODUCT_ID from PUR_PURCHASE_ARRIVED_ITEM ppai
left join PUR_PURCHASE_ORDER_ITEM ppoi on ppai.PURCHASE_ITEM_ID=ppoi.PURCHASE_ITEM_ID
where ppai.ARRIVED_ITEM_ID='" + dr["ARRIVED_ITEM_ID"].ToString() + "'"; 
                            m2.ProductId = broker.ExecuteSQLScalar(sql).ToString();
                            m2.Qty = Convert.ToDecimal(dr["CHECKED_QTY"].ToString());
                            m2.RelatedItemId = dr["ORDER_ITEM_ID"].ToString();
                            m2.Status = "IMPS01";
                            list.Add(m2);
                        }
                        DataAccess.Insert(m, broker);
                        DataAccess.Insert<InvImportItemEntity>(list, broker);
                    }
                    string sql2=@"update PUR_PURCHASE_ARRIVED set IS_QUALITYCHECKED=1
where ARRIVED_ID='"+entity.PurArrivedId+"'";
                    broker.ExecuteSQL(sql2);
                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
        }


        public static DataTable GetDtAllByCondition(string sCondition,string sRowCounts,string sOrderBy)
        {
            string sql = CommonFunctions.GetSelect(sRowCounts) + @" qio.*,ppa.ARRIVED_CODE from QC_IQC_ORDER qio
left join PUR_PURCHASE_ARRIVED ppa on qio.PUR_ARRIVED_ID=ppa.ARRIVED_ID
where 1=1 ";
            if (string.IsNullOrEmpty(sCondition) == false)
                sql += sCondition;
            if (string.IsNullOrEmpty(sOrderBy) == false)
                sql += sOrderBy;
            return DataAccess.SelectDataSet(sql).Tables[0];
        }

        public static bool IqcOrderConfirm(QcIqcOrderEntity entity)
        {
              using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    entity.Status = "STATUS06";
                    DataAccess.Update(entity, broker);
                    string sql = @"select * from PUR_REJECTED_ORDER pro
where pro.IQC_ORDER_ID='" + entity.OrderId + "'";
                    DataTable dt = DataAccess.SelectDataSet(sql).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        PurRejectedOrderEntity mRejectedOrder = new PurRejectedOrderEntity(dt.Rows[0]);
                        if (mRejectedOrder.RejectedType == 0)//部分拒收
                        {
                            InvImportOrderEntity m = new InvImportOrderEntity();
                            m.ImportOrderId = Guid.NewGuid().ToString();
                            m.OrderType = "IMT01";
                            string code = "";
                            if (MstCodeRuleBs.GetCurrentOrderCode("InvImportOrder", out code) == false)
                            {
                                broker.RollBack();
                                throw new Exception("自动生成质检单号失败！");
                            }
                            m.OrderCode = code;
                            m.OrderDate = DateTime.Now.ToString("yyyy-MM-dd");
                            m.OrderPerson = Common.CommonParameter.CurrentUser.PersonId;
                            m.RelatedOrder = entity.OrderId;
                            m.CreatedBy = Common.CommonParameter.CurrentUser.PersonId;
                            m.CreatedDate = DateTime.Now;
                            m.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                            m.LastModifiedDate = DateTime.Now;
                            m.Remark = "来料质检完成后，系统自动产生";
                            m.Status = "IMO01";

                            DataTable dtIqcOrderItem = QcIqcOrderItemBs.GetDtIqcOrderItemByOrderID(entity.OrderId);
                            List<InvImportItemEntity> list = new List<InvImportItemEntity>();
                            foreach(DataRow dr in dtIqcOrderItem.Rows)
                            {
                                InvImportItemEntity m2 = new InvImportItemEntity();
                                m2.ImportItemId = Guid.NewGuid().ToString();
                                m2.ImportOrderId = m.ImportOrderId;
                                sql = @"select ppoi.PRODUCT_ID from PUR_PURCHASE_ARRIVED_ITEM ppai
left join PUR_PURCHASE_ORDER_ITEM ppoi on ppai.PURCHASE_ITEM_ID=ppoi.PURCHASE_ITEM_ID
where ppai.ARRIVED_ITEM_ID='" + dr["ARRIVED_ITEM_ID"].ToString() + "'";
                                m2.ProductId = broker.ExecuteSQLScalar(sql).ToString();
                                m2.Qty = Convert.ToDecimal(dr["CHECKED_QTY"].ToString())-Convert.ToDecimal(dr["NG_QTY"].ToString());
                                m2.RelatedItemId = dr["ORDER_ITEM_ID"].ToString();
                                m2.Status = "IMPS01";
                                list.Add(m2);
                            }
                            DataAccess.Insert(m, broker);
                            DataAccess.Insert<InvImportItemEntity>(list, broker);
                        }
                    }
                    else
                    {
                        broker.RollBack();
                        return false;
                    }
                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
        }
        #endregion
    }


}

